from rest_framework import serializers
from apps.users.models import User

class AdminListSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
                'password': {
                    'write_only': True
                }
            }

    # 重写父类中的create方法
    def create(self, validated_data):

        # print(validated_data)
        # return User.objects.create_user(id=9, **validated_data)
        # user_permissions = validated_data.pop('user_permissions')
        # user = User.objects.create_user(**validated_data)
        # for user_permission in user_permissions:
        #     user.user_permission.add(user_permission)
        # return user

        admin = super().create(validated_data)
        password = validated_data.get('password')
        admin.set_password(password)
        admin.is_staff = True
        admin.save()
        return admin

    def update(self, instance, validated_data):

        super().update(instance, validated_data)
        password = validated_data.get('password')
        if password:
            instance.set_password(password)
            instance.save()
            return instance
        return instance
